<?php
class Admin_CategoryController extends ImpSoft_Controller_Action {

	public function init() {
		
		parent::init();
		$this->catTbl = new Category;
		$this->prdTbl = new Product;
	
	}
	/**
	 * Category selection page (for selecting a category to edit). Also to arrange
	 * the order and hierarchy of categories.
	 */
	public function listAction() {
	
		$query = $this->getRequest()->getQuery();
		$page = $this->getRequest()->getParam("page");
		$order = (empty($query['order'])) ? null : $query['order'];
		$dir = (empty($query['dir'])) ? null : $query['dir'];
		$this->view->dir = (strtolower($dir) == "asc") ? "desc" : "asc";
		$select = $this->catTbl->getListForAdmin($order, $dir);
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
		// @todo Eventually this should come from db settings
		$paginator->setItemCountPerPage(100);
		$paginator->setCurrentPageNumber($page);
		$this->view->categories = $paginator;
	
	}
	/**
	 * Reorder Categories
	 * This action allows the user to change the order that categories display
	 * on the application's front-end.
	 */
	public function reorderAction() {
	
		$page = $this->getRequest()->getParam('page');
		$select = $this->catTbl->getListForAdmin('order', 'asc');
		$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select));
		// @todo Pull from db settings
		$paginator->setItemCountPerPage(100);
		$paginator->setCurrentPageNumber($page);
		$this->view->categories = $paginator;
	
	}
	/**
	 * Set Order Category
	 * This is for setting a single category's order. It will automatically update
	 * (increase) the order for all subsequent categories. NULL order columns will
	 * come after all other categories. They will not be updated unless directly
	 * set with this function.
	 * @todo Setting a blank value should make the order column null. Right now it
	 *       does nothing
	 */
	public function setorderAction() {
	
		$category_id = $this->getRequest()->getParam('category_id');
		if ($this->isPost()) {
			try {
				$post = $this->getPost();
				// update all orders which are greater than this category's order and not null
				$this->catTbl->updateOrder($category_id, $post['order']);
			} catch (ImpSoft_Exception_CategoryNotFound $e) {
				$this->flash($e->getMessage(), 'error');
			}
		}
		// go to reorder page by default
		$this->goToRoute('admin_category_reorder');
	
	}
	/**
	 * Add category
	 */
	public function addAction() {
	
		$category = $this->catTbl->createRow();
		// build filters from table
		$filters = with(new Q_Filter_Set())
			->add($this->catTbl->getFilters());
		// build rules from table
		$rules = with(new Q_Rule_Set())
			->add($this->catTbl->getRules());
		// initialize the errors array
		$errors = array();
		// if data has been posted, handle it
		if ($this->isPost()) {
			$post = $this->getPost();
			// filter post data
			$post = $filters->filter($post);
			// validate filtered data
			if ($rules->validate($post)) {
				$category->setFromArray($post);
				$category->is_active = true;
				if (empty($category->parent_id)) {
					$category->parent_id = new Zend_Db_Expr("NULL");
				}
				// begin database transaction
				$this->db->beginTransaction();
				try {
					$category->save();
					// commit any queries
					$this->db->commit();
					$this->flash("Category was created successfully", "notice");
					$this->goToRoute("admin_category_add");
					return;
				} catch (Zend_Db_Exception $e) {
					// if any data couldn't be saved, roll back everything
					$this->db->rollback();
					$this->flash("Category could not be saved, sorry!", "error");
					$this->goToRoute("admin_category_add");
					return;
				}
			} else {
				$errors = $rules->getErrors();
			}
		}
		$this->view->errors = $errors;
		$this->view->categories = $this->catTbl->getListForSelect();
		$this->view->required = $rules->getRequired();
		$this->view->category = $category->toArray();
	
	}
	/**
	 * Edit category
	 */
	public function editAction() {
	
		$category_id = $this->getRequest()->getParam('category_id');
		$this->view->tab = $this->getRequest()->getParam('tab');
		$catset = $this->catTbl->find($category_id);
		if (!$catset->count()) {
			$this->flash("The category you attempted to edit doesn't exist.");
			$this->goToRoute("admin_category_list");
			return;
		}
		$category = $catset->current();
		// build filters from table
		$filters = with(new Q_Filter_Set())
			->add($this->catTbl->getFilters());
		// build rules from table
		$rules = with(new Q_Rule_Set())
			->add($this->catTbl->getRules());
		$errors = array();
		if ($this->isPost()) {
			$post = $this->getPost();
			// filter post data
			$post = $filters->filter($post);
			// validate filtered data
			if ($rules->validate($post)) {
				$category->setFromArray($post);
				// begin database transaction
				$this->db->beginTransaction();
				try {
					$category->save();
					// commit any queries
					$this->db->commit();
					$this->flash("Category was updated successfully", "success");
					$this->goToRoute("admin_category_edit", array("category_id" => $category->category_id));
					return;
				} catch (Zend_Db_Exception $e) {
					// if any data couldn't be saved, roll back everything
					$this->db->rollback();
					$this->flash("Category could not be saved, sorry!", "error");
					$this->goToRoute("admin_category_edit", array("category_id" => $category->category_id));
					return;
				}
			} else {
				$errors = $rules->getErrors();
			}
		}
		$this->view->errors = $errors;
		$catselect = $this->catTbl->select()->where("category_id <> ?", $category_id)->where("is_active = ?", true);
		$this->view->categories = $this->catTbl->getListForSelect($catselect);
		$this->view->required = $rules->getRequired();
		$this->view->category = $category->toArray();
	
	}
	/**
	 * Delete a category
	 */
	public function deleteAction() {

		$category_id = $this->getRequest()->getParam('category_id');
		$this->catTbl->delete($this->catTbl->getAdapter()->quoteInto('category_id = ?', $category_id));
		$this->flash("Category was deleted successfully");
		$this->goToRoute("admin_category_list");

	}
	/**
	 * Deactivate a category
	 */
	public function deactivateAction() {

		$category_id = $this->getRequest()->getParam('category_id');
		$where = $this->db->quoteInto('category_id = ?', $category_id);
		$this->db->update($this->catTbl->info('name'), array('is_active' => 'FALSE'), $where);
		$this->flash("Category was deactivated successfully");
		$this->goToRoute("admin_category_edit", array('category_id' => $category_id));

	}
	/**
	 * Activate a category
	 */
	public function activateAction() {

		$category_id = $this->getRequest()->getParam('category_id');
		$where = $this->db->quoteInto('category_id = ?', $category_id);
		$this->db->update($this->catTbl->info('name'), array('is_active' => 'TRUE'), $where);
		$this->flash("Category was activated successfully");
		$this->goToRoute("admin_category_edit", array('category_id' => $category_id));

	}

}
?>